package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录请求
 */
@Slf4j
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    EmpService empService;

    //登录操作
    @PostMapping
    public Result login(@RequestBody Emp emp) {
        Emp e = empService.login(emp);
        if (e != null) {
            //说明登录成功，生成jwt令牌，下发
            Map<String, Object> map = new HashMap<>();
            map.put("id", e.getId());
            map.put("username", e.getUsername());
            String jwt = JwtUtils.generateJwt(map);
            //将jwt字符串响应给浏览器
            return Result.success(jwt);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

}
